package org.fing.edu.uy.esbadp.action.gateway;

import java.util.logging.Level;

import org.fing.edu.uy.esbadp.core.AdpFlowConstants;
import org.fing.edu.uy.esbadp.core.AdpFlowInterface;
import org.fing.edu.uy.esbadp.core.AdpFlowTree;
import org.fing.edu.uy.esbadp.core.entity.GenericTreeNode;
import org.fing.edu.uy.esbadp.logger.LoggerADP;
import org.fing.edu.uy.esbadp.modules.admAdaptation.AdpAdministrator;
import org.jboss.internal.soa.esb.assertion.AssertArgument;
import org.jboss.soa.esb.actions.ActionProcessingException;
import org.jboss.soa.esb.actions.annotation.Process;
import org.jboss.soa.esb.client.ServiceInvoker;
import org.jboss.soa.esb.message.Message;

public class GatewayAction {

	private static java.util.logging.Logger logger = LoggerADP.getLogger(GatewayAction.class.getSimpleName());

	public GatewayAction() {
		
	}
	
	/**
	 * @param message
	 */
	@Process
	public Message process(Message message) throws ActionProcessingException {
		AssertArgument.isNotNull(message, "message");
		
		try{
			AdpAdministrator adpAdmin = AdpAdministrator.getInstance();
			AdpFlowTree adpFlowTree =  adpAdmin.getAdaptationFlowTree(message);
	
			//se agrega la lista de servicios a invocar en el flow
			message.getProperties().setProperty(AdpFlowConstants.PropertyFlowServices, adpFlowTree);
				
			//invoca al primer servicio de la lista generada por el AdpAdministrator
			GenericTreeNode<AdpFlowInterface> treeNode = adpFlowTree.getCurrent();
			AdpFlowInterface adpService = treeNode.getData();
			String serviceCategory = adpService.getServiceCategoryName();
			String serviceName = adpService.getServiceName();
	
			//delivero mensaje async para el primer servicio de la lista
			ServiceInvoker service = new ServiceInvoker(serviceCategory, serviceName);
			service.deliverAsync(message);
		}catch (Exception ex) {
			logger.log(Level.SEVERE, "Exception in GatewayAction.", ex);
			throw new ActionProcessingException(ex.getMessage());
		}
		return null;
	}
	
}
